package com.bcbim.common.lz;

import com.bcbim.common.compress.Compress;
import com.google.common.primitives.Bytes;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.*;

/**
 * @Description: 解压方法
 * @Author: ye
 * @Date: 2022/4/7
 * @Version: V1.0
 **/
public class LzUtils {

    /**
     * @Description: 解压方法
     * @Param: byte[] 压缩字节
     * @Return: String
     * @Author: ye
     * @Date: 2022/4/7
     */
    public static String decompress(byte[] bytes) throws UnsupportedEncodingException {
        List<Byte> resultBytes = new ArrayList<>();
        Map<Integer, List<Byte>> dictionary = new HashMap();
        int dictionaryIndex = 1;
        for (int i = 0; i < bytes.length; i += 3) {

            int index = ((bytes[i] & 0xff) << 8 ) | (bytes[i + 1] & 0xff);
            List<Byte> arrTemp = new ArrayList<>();
            if (index != 0) {
                List<Byte> bytes1 = dictionary.get(index);
                resultBytes.addAll(bytes1);
                arrTemp.addAll(bytes1);
            }
            resultBytes.add(bytes[i + 2]);
            arrTemp.add(bytes[i + 2]);

            dictionary.put(dictionaryIndex, arrTemp);
            if (dictionaryIndex > 65535) {
                dictionaryIndex = 1;
            }else{
                dictionaryIndex++;
            }
        }
        return new String(Bytes.toArray(resultBytes), "UTF-8");
    }

    public static void main(String[] args) throws IOException {
        Path infoPath = Paths.get("D:\\Program Files\\apache-tomcat-8.5.66\\webapps\\model\\gra_0.txt");
        byte[] data = Files.readAllBytes(infoPath);
        System.out.println(data.length);
        System.out.println(LocalDateTime.now());
//            String decompress = LzUtils.decompress(data);
        Compress compress = new Compress();
        byte[] bytes = compress.compressData(data);
        FileOutputStream out = new FileOutputStream("D:\\Program Files\\apache-tomcat-8.5.66\\webapps\\model\\77Compress.txt");
        out.write(bytes);
        System.out.println(bytes.length);
        System.out.println(LocalDateTime.now());
    }
}
